package Concurrent.Condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by wangyg6 on 2017/11/30.
 * 编写一个程序，开启 3 个线程，这三个线程的 ID 分别为 A、B、C，
 * 每个线程将自己的 ID 在屏幕上打印 10 遍，
 * 要求输出的结果必须按顺序显示。如：ABCABCABC……
 */
public class QuesDemo {
	static String flag = "A";

	public static void main(String[] args) {
		ReentrantLock lock = new ReentrantLock();
		Condition a = lock.newCondition();
		Condition b = lock.newCondition();
		Condition c = lock.newCondition();

		new Thread("A") {
			@Override
			public void run() {
				lock.lock();
				try {
					for (int i = 1; i <= 10; i++) {
						while (!"A".equals(flag)) {
							a.await();
						}
						System.out.print(Thread.currentThread().getName());
						b.signal();
						flag = "B";
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}.start();
		new Thread("B") {
			@Override
			public void run() {
				lock.lock();
				try {
					for (int i = 1; i <= 10; i++) {
						while (!"B".equals(flag)) {
							b.await();
						}
						System.out.print(Thread.currentThread().getName());
						c.signal();
						flag = "C";
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}

		}.start();
		new Thread("C") {
			@Override
			public void run() {
				lock.lock();
				try {
					for (int i = 1; i <= 10; i++) {
						while (!"C".equals(flag)) {
							c.await();
						}
						System.out.print(Thread.currentThread().getName());
						a.signal();
						flag = "A";
					}

				} catch (InterruptedException e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
				}
			}
		}.start();
	}

}
